package com.smart_campus.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.smart_campus.sys.common.*;
import com.smart_campus.sys.domain.User;
import com.smart_campus.sys.domain.UserInfo;
import com.smart_campus.sys.service.UserInfoService;
import com.smart_campus.sys.service.UserService;
import com.smart_campus.sys.vo.UserANDRoleANDDeptVO;
import com.smart_campus.sys.vo.UserAndUserInfoVo;
import com.smart_campus.sys.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author:Omega
 * @Date:2020/6/8 8:15
 */

@Controller
@RequestMapping("User")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;



    /**
     * 注册
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("UserAdd")
    @ResponseBody
    public ResultObj userAdd(String username, String password,String identity) {
        User user = new User();
        user.setRole(UserEntity.USER_ROLE);
        user.setUsername(username);
        user.setPassword(password);
        UserInfo userInfo = new UserInfo();
        userInfo.setIdentity(identity);
        //先判断身份证是否已注册
        UserInfo ui;
        ui=userInfoService.selectByUserInfo(userInfo);
        try{
        if (!StringUtils.isBlank(ui.getIdentity())){
            return ResultObj.IDENTITY_EXIST;
        }
        }catch (Exception e){
        }
        //身份证和用户名是否有效
        if (!identityVerify.verification(username,identity)){
            return ResultObj.IDENTITY_FALSE;
        }
        return userService.insertUserAndINfo(user,userInfo);
    }


    /**
     * 短信注册
     *
     * @param phone
     * @param sms
     * @return
     */
    @RequestMapping("SmsUserADD")
    @ResponseBody
    public ResultObj smsUserADD(String phone, String sms) {
        String code = redisTemplate.opsForValue().get(phone);
        try {
            if (code.equals(sms)) {
                User user = new User();
                user.setPhone(phone);
                return userService.insertUser(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultObj(-1, "添加失败");
        }
        return new ResultObj(-1, "添加失败");
    }

    /**
     * 短信验证码
     *
     * @return
     */
    @RequestMapping("smsCode")
    @ResponseBody
    public ResultObj smsCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            return new ResultObj(-1, "请输入手机号");
        }
        //判断手机号是否被注册过
        if (!userService.queryUserByPhone(phone)) {
            return new ResultObj(-1, "该手机号已被注册！");
        }
        //调用方法
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return new ResultObj(-2, "验证码还能继续使用，你丫的就是想坑我的钱！");
        }
        //生成验证码并存储到redis中
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, String> param = new HashMap<>();
        param.put("code", code);
        Boolean isSend = SmsCode.SendSms(phone, "SMS_192542394", param);
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 60, TimeUnit.SECONDS);
            return new ResultObj(200, "发送成功请注意查看短信");
        } else {
            return new ResultObj(-3, "发送失败");
        }
    }

    //实名找回密码
    @RequestMapping("retrievePassword")
    @ResponseBody
    public ResultObj retrievePassword(String username,String loginname,String password,String identity){
        if (StringUtils.isNotBlank(username)&&StringUtils.isNotBlank(loginname)&&StringUtils.isNotBlank(password)&&StringUtils.isNotBlank(identity)){
            return userService.autonymRetrieve(username,loginname,password,identity);
        }
        return ResultObj.RESET_SUCCESS;
    }

    /**
     * 短信验证码
     *找回密码，不会判断该手机号是否注册过
     * @return
     */
    @RequestMapping("retrieveSMSCode")
    @ResponseBody
    public ResultObj retrieveSMSCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            return new ResultObj(-1, "请输入手机号");
        }
        if (userService.queryUserByPhone(phone)){
            return new ResultObj(-1, "请输入正确的手机号");
        }
        //调用方法
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return new ResultObj(-2, "验证码还能继续使用，你丫的就是想坑我的钱！");
        }
        //生成验证码并存储到redis中
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, String> param = new HashMap<>();
        param.put("code", code);
        Boolean isSend = SmsCode.SendSms(phone, "SMS_192542394", param);
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 60, TimeUnit.SECONDS);
            return new ResultObj(200, "发送成功请注意查看短信");
        } else {
            return new ResultObj(-3, "发送失败");
        }
    }

    /**
     *短信修改密码
     *
     * @param phone
     * @param sms
     * @param password
     * @return
     */
    @RequestMapping("retrieveSMSPassowrd")
    @ResponseBody
    public ResultObj retrieveSMSPassowrd(String phone, String sms, String password) {
        String code = redisTemplate.opsForValue().get(phone);
        try {
            if (code.equals(sms)) {
                User user = new User();
                user.setPhone(phone);
                user.setPassword(password);
                return userService.phoneUpdatePassword(user);
            }
        } catch (Exception e) {
            return new ResultObj(-1, "验证失败");
        }
        return new ResultObj(-1, "验证失败");
    }






    /**
     * 添加员工
     *
     * @return
     */
    @RequestMapping("addUser")
    @ResponseBody
    public ResultObj addUser(User user){
        System.out.println(user.getUsername());
            return userService.insertstaff(user);
    }


    /**
     * 查询全部用户
     * @param userVo
     * @return
     */
    @RequestMapping("UserList")
    @ResponseBody
    public DataGridView UserList(UserVo userVo){
        return userService.selectUser(userVo);
    }

    /**
     * 删除用户和相关信息
     * @param id
     * @return ResultObj
     */
    @RequiresPermissions("user:delete")
    @RequestMapping("UserDelete")
    @ResponseBody
    public ResultObj UserDelete(Integer id){
        try {
            userService.deleteUser(id);
            return ResultObj.DELETE_USER_YES;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_USER_NO;
        }
    }

    /**
     * 批量删除用户和相关信息
     * @param ids
     * @return ResultObj
     * 11
     */
    @RequiresPermissions("user:deletebatch")
    @RequestMapping("DeleteBatchUser")
    @ResponseBody
    public ResultObj DeleteBatchUser(Integer[] ids){
        try {
            for (Integer id:ids) {
                userService.deleteUser(id);
            }
            return ResultObj.DELETE_USER_YES;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_USER_NO;
        }
    }

    /**
     * 添加用户的角色
     * @param uid
     * @param rids
     * @return
     */
    @RequiresPermissions("user:allot")
    @RequestMapping("saveUserRole")
    @ResponseBody
    public ResultObj saveUserRole(Integer uid ,Integer[] rids){
        try {
            userService.deleteUserRole(uid);
            for (Integer id:rids) {
                userService.insertUserRole(uid,id);
            }
            return ResultObj.UPDATE_USER_ROLE_YES;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_USER_ROLE_NO;
        }
    }


    /**
     * 修改用户的详细信息
     * @param userANDRoleANDDeptVO
     * @return ResultObj
     */
//    @RequiresPermissions("user:update")
    @RequestMapping("updateUser")
    @ResponseBody
    public ResultObj updateUser(UserANDRoleANDDeptVO userANDRoleANDDeptVO){
        try {
            userService.UserANDRoleANDDeptVOUPATE(userANDRoleANDDeptVO);
            return ResultObj.UserANDRoleANDDeptVO_YES;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UserANDRoleANDDeptVO_NO;
        }
    }


    /**
     * 前台修改
     * @param userANDRoleANDDeptVO
     * @return
     */
    @RequestMapping("updateUserTwo")
    @ResponseBody
    public ResultObj updateUserTwo(UserANDRoleANDDeptVO userANDRoleANDDeptVO){
        try {
            userService.UserANDRoleANDDeptVOUPATE(userANDRoleANDDeptVO);
            return ResultObj.UserANDRoleANDDeptVO_YES;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UserANDRoleANDDeptVO_NO;
        }
    }


    /**
     * 修改是否可用
     * @param id
     * @param available
     * @return ResultObj
     */
    @RequestMapping("updateAvailable")
    @ResponseBody
    public ResultObj updateAvailable(Integer id,Integer available){
        try {
            userService.updateAvailable(id,available);
            return ResultObj.UserANDRoleANDDeptVO_YES;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UserANDRoleANDDeptVO_NO;
        }
    }


    /**
     * 重置密码
     * @param id
     * @return
     */
    @RequestMapping("resetUserPwd")
    @ResponseBody
    public ResultObj resetUserPwd(Integer id){
        try {
            userService.updateUserPwd(id);
            return ResultObj.UserANDRoleANDDeptVO_YES;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UserANDRoleANDDeptVO_NO;
        }
    }


    /**
     * 查询登入用户
     * @return
     */
    @RequestMapping("getCurrentUser")
    @ResponseBody
    public DataGridView getCurrentUser(){
        return userService.getCurrentUser();
    }

    /**
     * 查询登入用户的全部信息
     * @return
     */
    @RequestMapping("getUserPhoneIdentity")
    @ResponseBody
    public UserAndUserInfoVo getUserPhoneIdentity(){
        return userService.getUserPhoneIdentity();
    }

    /**
     * 查询登入用户
     * @return
     */
    @RequestMapping("getUser")
    @ResponseBody
    public DataGridView getUser(Integer id){
        return userService.getUser(id);
    }

}
